package com.yyy.dm.filter;

import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.yyy.dm.JWTUtils;
import org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration;
import org.springframework.boot.autoconfigure.web.servlet.DispatcherServletPath;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Map;
@Component
public class AuthFilter implements GlobalFilter,Ordered {

    private static final long KEEP_TIME = 5*60*1000;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        if (! request.getURI().getPath().contains("/permission")) {
            return chain.filter(exchange);
        }
        String oldToken = request.getHeaders().getFirst("token");
        ServerHttpResponse response = exchange.getResponse();
        //用户没有登录直接响应
        if (oldToken==null) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //用户登录了检验token剩余时间
        try {
            DecodedJWT verify = JWTUtils.verify(oldToken);
            Map<String, Claim> claims = verify.getClaims();
            Long expireTime = claims.get("exp").asDate().getTime();
            Long nowTime = System.currentTimeMillis();
            if(expireTime - nowTime <= KEEP_TIME){
                //置换token
                Map map = claims.get("loginUser").asMap();
                String newToken = JWTUtils.getToken("loginUser",map);
                response.getHeaders().add("token",newToken);
            }
        } catch (TokenExpiredException e){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        return chain.filter(exchange.mutate()
                .response(response)
                .build());
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
